package user

import (
	"github.com/gin-gonic/gin"

	"github.com/runningwater/gohub/pkg/app"
	"github.com/runningwater/gohub/pkg/database"
	"github.com/runningwater/gohub/pkg/paginator"
)

// IsEmailExist 检查邮箱是否已存在
func IsEmailExist(email string) bool {
	var count int64
	database.DB.Model(&User{}).Where("email = ?", email).Count(&count)
	return count > 0
}

// IsPhoneExist 检查手机号是否已存在
func IsPhoneExist(phone string) bool {
	var count int64
	database.DB.Model(&User{}).Where("phone = ?", phone).Count(&count)
	return count > 0
}

// GetByMulti 多条件查询，支持手机号、邮箱和用户名
// 按顺序检查并返回第一个匹配的用户
func GetByMulti(loginID string) (userModel User) {
	database.DB.
		Where("phone = ?", loginID).
		Or("email =?", loginID).
		Or("name =?", loginID).
		First(&userModel)

	return
}

// GetByPhone 根据手机号查询用户
func GetByPhone(phone string) (userModel User) {
	database.DB.Where("phone = ?", phone).First(&userModel)
	return
}

// Get 根据 ID 查询用户
func Get(idStr string) (userModel User) {
	database.DB.Where("id =?", idStr).First(&userModel)
	return
}

// All 查询所有用户
func All() (users []User) {
	database.DB.Find(&users)
	return
}

// Paginate 分页内容
func Paginate(c *gin.Context, pageSize int) (users []User, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(User{}),
		&users,
		app.V1URL(database.TableName(&User{})),
		pageSize,
	)
	return
}
